﻿using Nop.Core.Infrastructure;
using Nop.Services.Logging;
using Nop.Services.Tasks;
using System;

namespace Nop.Services.WindAlert
{
    /// <summary>
    /// Represents a task for sending queued message 
    /// </summary>
    public partial class UpdateForecastSpotTask : ITask
    {

        /// <summary>
        /// Executes a task
        /// </summary>
        public void Execute()
        {
            var spotService = EngineContext.Current.Resolve<ISpotService>();
            var forecastDataService = EngineContext.Current.Resolve<IForecastDataService>();

            var spots = spotService.GetAllSpots(isForecast:true);
            
            foreach (var spot in spots)
            {
                try
                {
                    if (spot.IsForecast)
                    {
                        var forecastDatas = forecastDataService.UpdateForecastSpot(spot);
                        if (forecastDatas != null)
                        {
                            foreach (var forecastData in forecastDatas)
                            {
                                if (forecastDataService.ForecastNameExists(forecastData.Name, spot.Id))
                                {
                                    var CurrentforecastData = forecastDataService.GetForecastDataBySpotIdAndName(spot.Id, forecastData.Name);
                                    CurrentforecastData.CreatedOnUtc = forecastData.CreatedOnUtc;
                                    CurrentforecastData.ForecastTime = forecastData.ForecastTime;
                                    CurrentforecastData.WindSpeed = forecastData.WindSpeed;
                                    CurrentforecastData.WindDirection = forecastData.WindDirection;
                                    CurrentforecastData.Height = forecastData.Height;
                                    CurrentforecastData.Period = forecastData.Period;
                                    CurrentforecastData.WaveDirection = forecastData.WaveDirection;
                                    forecastDataService.UpdateForecastData(CurrentforecastData);
                                }
                                else
                                {
                                    forecastDataService.InsertForecastData(forecastData);
                                }
                            }
                        }
                    }
                }
                catch (Exception exc)
                {
                    var logger = EngineContext.Current.Resolve<ILogger>();
                    logger.Error(string.Format("Error updateing spots. {0}", exc.Message), exc);
                    continue;
                }
                
            }
        }
    }
}
